package com.reebake.ideal.captcha.controller;

import com.reebake.ideal.captcha.core.SmartCaptchaService;
import com.reebake.ideal.captcha.entity.CaptchaRequestEntity;
import com.reebake.ideal.captcha.entity.CaptchaResponseEntity;
import com.reebake.ideal.servlet.util.WebUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("captcha")
@RequiredArgsConstructor
public class CaptchaController {
    private final SmartCaptchaService smartCaptchaService;

    @PostMapping("get")
    public CaptchaResponseEntity get(HttpServletRequest request, @RequestBody CaptchaRequestEntity data) {
        assert request.getRemoteHost()!=null;
        data.setBrowserInfo(getRemoteId(request));
        return smartCaptchaService.get(data);
    }

    @PostMapping("/check")
    public CaptchaResponseEntity check(@RequestBody CaptchaRequestEntity data, HttpServletRequest request) {
        data.setBrowserInfo(getRemoteId(request));
        return smartCaptchaService.check(data);
    }

    public static String getRemoteId(HttpServletRequest request) {
        String ip = WebUtil.getClientIP();
        String ua = request.getHeader(HttpHeaders.USER_AGENT);
        return ip + ua;
    }

}
